package com.itheima.bakery.demos.web.service;

import com.itheima.bakery.demos.web.Repositories.UserRepository;
import com.itheima.bakery.demos.web.model.Product;
import com.itheima.bakery.demos.web.Repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private UserRepository userRepository;

    public List<Product> findAllProducts() {
        return productRepository.findAll();
    }

    public Optional<Product> findProductById(Integer id) {
        return productRepository.findById(id);
    }

    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    public boolean deleteProduct(Integer id) {
        try {
            productRepository.deleteById(id);
            return true;
        } catch (EmptyResultDataAccessException e) {
            // 捕获异常，表示删除失败，因为记录不存在
            return false;
        }
    }

    public Product getProductById(Integer id) {
        return productRepository.findById(id).orElse(null);
    }

    public List<Product> searchProductsByProductNameContaining(String query) {
        return productRepository.findByNameContainingIgnoreCase(query);
    }
    public List<Product> searchProductsByDescriptionContainingIgnoreCase(String query) {
        return productRepository.searchProductsByDescriptionContainingIgnoreCase(query);
    }
}
